<template>
    <div class="dashboard-container">
        <Navbar />

        <div class="content-wrapper" v-loading="loading">
            <template v-if="overviewData">
                <div class="system-status-container">
                    <div class="system-status-row">
                        <div class="status-main">
                            <span class="status-badge" :class="overviewData.system_status.status">
                                {{ getStatusText(overviewData.system_status.status) }}
                            </span>
                            <span class="running-days">运行天数: {{ overviewData.core_metrics.running_days }} 天</span>
                        </div>
                        <div class="status-details">
                            <span>更新于: {{ formatTime(overviewData.system_status.last_update_time) }}</span>
                            <span class="error-count">
                                报错: {{ overviewData.system_status.error_count }}
                            </span>
                            <span class="warning-count">
                                警告: {{ overviewData.system_status.warning_count }}
                            </span>
                        </div>
                    </div>
                </div>

                <el-row :gutter="20" class="l1-periodic-metrics-row">
                    <el-col :lg="8" :md="24">
                        <el-card shadow="hover" class="periodic-metric-card">
                            <template #header>
                                <div class="card-header">
                                    <el-icon>
                                        <Calendar />
                                    </el-icon> 今日概览
                                </div>
                            </template>
                            <el-statistic title="今日收益 (USD)" :value="overviewData.system_status.today_profit"
                                :precision="2"
                                :value-style="overviewData.system_status.today_profit >= 0 ? { color: 'var(--el-color-success)' } : { color: 'var(--el-color-danger)' }">
                            </el-statistic>
                            <div class="periodic-sub-metric">
                                <span>今日收益率: {{ formatPercent(overviewData.system_status.today_return) }}</span>
                                <span>今日交易: {{ overviewData.system_status.today_trades }} 笔</span>
                            </div>
                        </el-card>
                    </el-col>

                    <el-col :lg="8" :md="12">
                        <el-card shadow="hover" class="periodic-metric-card">
                            <template #header>
                                <div class="card-header">
                                    <el-icon>
                                        <CollectionTag />
                                    </el-icon> 本周概览
                                </div>
                            </template>
                            <el-statistic title="本周收益 (USD)" :value="overviewData.system_status.week_profit"
                                :precision="2"
                                :value-style="overviewData.system_status.week_profit >= 0 ? { color: 'var(--el-color-success)' } : { color: 'var(--el-color-danger)' }">
                            </el-statistic>
                            <div class="periodic-sub-metric">
                                <span>本周收益率: {{ formatPercent(overviewData.system_status.week_return) }}</span>
                                <span>本周交易: {{ overviewData.system_status.week_trades }} 笔</span>
                            </div>
                        </el-card>
                    </el-col>

                    <el-col :lg="8" :md="12">
                        <el-card shadow="hover" class="periodic-metric-card">
                            <template #header>
                                <div class="card-header">
                                    <el-icon>
                                        <Wallet />
                                    </el-icon> 本月概览
                                </div>
                            </template>
                            <el-statistic title="本月收益 (USD)" :value="overviewData.system_status.month_profit"
                                :precision="2"
                                :value-style="overviewData.system_status.month_profit >= 0 ? { color: 'var(--el-color-success)' } : { color: 'var(--el-color-danger)' }">
                            </el-statistic>
                            <div class="periodic-sub-metric">
                                <span>本月收益率: {{ formatPercent(overviewData.system_status.month_return) }}</span>
                                <span>本月交易: {{ overviewData.system_status.month_trades }} 笔</span>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>


                <el-row :gutter="20">

                    <el-col :lg="8" :md="24">
                        <el-card shadow="always" class="stretch-card">
                            <template #header>
                                <div class="card-header">资金状态</div>
                            </template>
                            <div class="capital-highlight">
                                <el-statistic title="当前总资金" :value="overviewData.capital_status.total_equity"
                                    :precision="2" />
                            </div>
                            <div ref="capitalDistChartRef" class="pie-chart-container"></div>
                            <el-descriptions :column="1" border class="capital-details">
                                <el-descriptions-item label="初始资金">{{
                                    formatCurrency(overviewData.capital_status.initial_capital)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="累计盈利">{{
                                    formatCurrency(overviewData.capital_status.total_profit)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="可用余额">{{
                                    formatCurrency(overviewData.capital_status.available_balance)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="已用保证金">{{
                                    formatCurrency(overviewData.capital_status.used_margin)
                                }}</el-descriptions-item>
                                <el-descriptions-item label="已用保证金率">
                                    <span class="profit-loss-text">
                                        {{ formatPercent(overviewData.capital_status.margin_ratio, 2) }}
                                    </span>
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-card>
                    </el-col>


                    <el-col :lg="16" :md="24">
                        <el-card shadow="always" class="stretch-card">
                            <template #header>
                                <div class="card-header">月度收益历史</div>
                            </template>
                            <div ref="monthlyReturnChartRef" class="chart-container-secondary"></div>
                        </el-card>
                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :lg="12" :md="24">
                        <el-card shadow="always" class="stretch-card">
                            <template #header>
                                <div class="card-header">资金费率策略 (贡献: {{ overviewData.funding_strategy.contribution
                                }}%)
                                </div>
                            </template>
                            <el-descriptions :column="2" border class="strategy-description">
                                <el-descriptions-item label="月收益率">
                                    <span
                                        :class="overviewData.funding_strategy.monthly_return >= 0 ? 'profit-cell' : 'loss-cell'">
                                        {{ formatPercent(overviewData.funding_strategy.monthly_return, 2) }}
                                    </span>
                                </el-descriptions-item>
                                <el-descriptions-item label="APY">{{
                                    formatPercent(overviewData.funding_strategy.apy)
                                }}</el-descriptions-item>
                            </el-descriptions>
                            <el-table :data="overviewData.funding_strategy.positions" stripe class="strategy-table"
                                max-height="250">
                                <el-table-column prop="symbol" label="交易对" width="140" />
                                <el-table-column prop="size" label="仓位(USD)"
                                    :formatter="(row: any) => formatCurrency(row.size)" />
                                <el-table-column prop="current_pnl" label="当前盈亏">
                                    <template #default="scope">
                                        <span
                                            :class="{ 'text-positive': scope.row.current_pnl > 0, 'text-negative': scope.row.current_pnl < 0 }">
                                            {{ formatCurrency(scope.row.current_pnl) }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="current_pnl_rate" label="当前盈亏率" width="140">
                                    <template #default="scope">
                                        <span class="profit-loss-text">
                                            {{ formatPercent(scope.row.current_pnl_rate, 2) }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="entry_time" label="进入时间" width="160"
                                    :formatter="(row: any) => formatTime(row.entry_time)" />
                            </el-table>
                        </el-card>
                    </el-col>


                    <el-col :lg="12" :md="24">
                        <el-card shadow="always" class="stretch-card">
                            <template #header>
                                <div class="card-header">价差策略 (贡献: {{ overviewData.spread_strategy.contribution }}%)
                                </div>
                            </template>
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="月收益率">
                                    <span
                                        :class="overviewData.spread_strategy.monthly_return >= 0 ? 'profit-cell' : 'loss-cell'">
                                        {{ formatPercent(overviewData.spread_strategy.monthly_return, 2) }}
                                    </span>
                                </el-descriptions-item>
                                <el-descriptions-item label="APY">
                                    <span class="profit-loss-text">
                                        {{ formatPercent(overviewData.spread_strategy.apy, 2) }}
                                    </span>
                                </el-descriptions-item>
                                <el-descriptions-item label="机会次数">{{
                                    overviewData.spread_strategy.opportunities_count
                                }}</el-descriptions-item>
                                <el-descriptions-item label="平均盈利">
                                    <span class="profit-loss-text"
                                        :class="overviewData.spread_strategy.avg_profit_per_trade >= 0 ? 'profit-cell' : 'loss-cell'">
                                        {{ formatPercent(overviewData.spread_strategy.avg_profit_per_trade, 2) }}
                                    </span>
                                </el-descriptions-item>
                                <el-descriptions-item label="平均持仓" :span="2">{{
                                    overviewData.spread_strategy.avg_holding_duration
                                }}</el-descriptions-item>
                            </el-descriptions>
                            <el-table :data="overviewData.spread_strategy.active_positions" stripe
                                class="strategy-table" max-height="250">
                                <el-table-column prop="symbol" label="交易对" width="120" />
                                <el-table-column label="做多" prop="exchange_long" />
                                <el-table-column label="做空" prop="exchange_short" />
                                <el-table-column label="百分比价差" prop="current_spread">
                                    <template #default="scope">
                                        <span>
                                            {{ formatPercent(scope.row.current_spread, 2) }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="size" label="仓位(USD)"
                                    :formatter="(row: any) => formatCurrency(row.size)" />
                                <el-table-column prop="current_pnl" label="当前盈亏">
                                    <template #default="scope">
                                        <span
                                            :class="{ 'profit-cell': scope.row.current_pnl > 0, 'loss-cell': scope.row.current_pnl < 0 }">
                                            {{ formatCurrency(scope.row.current_pnl) }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="持仓时间" prop="holding_duration" />
                                <el-table-column label="进入时间" prop="entry_time" width="160"
                                    :formatter="(row: any) => formatTime(row.entry_time)" />
                            </el-table>
                        </el-card>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :lg="24" :md="24">
                        <el-card shadow="always" class="stretch-card">
                            <template #header>
                                <div class="card-header">核心指标与风险概况</div>
                            </template>
                            <div class="metrics-container">
                                <!-- 核心指标区域 -->
                                <div class="metrics-section core-metrics">
                                    <div class="kpi-group-title">核心指标</div>
                                    <div class="metrics-content">
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">总收益额 (USD)</span>
                                            <span class="kpi-item-value profit-positive">{{
                                                formatCurrency(overviewData.core_metrics.total_profit_amount) }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">总收益率</span>
                                            <span class="kpi-item-value">{{
                                                formatPercent(overviewData.core_metrics.total_return_rate) }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">年化收益率 (APY)</span>
                                            <span class="kpi-item-value profit-positive">{{
                                                formatPercent(overviewData.core_metrics.apy)
                                            }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">运行天数</span>
                                            <span class="kpi-item-value">{{ overviewData.core_metrics.running_days }}
                                                天</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- 风险指标区域 -->
                                <div class="metrics-section risk-metrics">
                                    <div class="kpi-group-title">风险指标</div>
                                    <div class="metrics-content">
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">最大回撤</span>
                                            <span class="kpi-item-value profit-negative">{{
                                                formatPercent(overviewData.risk_metrics.max_drawdown) }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">夏普比率</span>
                                            <span class="kpi-item-value">{{ overviewData.risk_metrics.sharpe_ratio
                                            }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">总胜率</span>
                                            <span class="kpi-item-value">{{
                                                formatPercent(overviewData.risk_metrics.win_rate)
                                            }}</span>
                                        </div>
                                        <div class="kpi-item">
                                            <span class="kpi-item-label">年化波动率</span>
                                            <span class="kpi-item-value">{{
                                                formatPercent(overviewData.risk_metrics.annual_volatility) }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </template>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, shallowRef, nextTick, computed } from 'vue';

// 获取状态文本
const getStatusText = (status: string): string => {
    if (status === 'running') return '运行中';
    if (status === 'wait') return '扫描中';
    return '已停止';
};

import { getOverview } from '../services/api/Home/overview';

import Navbar from '../components/Navbar.vue';
import type { EChartsOption } from 'echarts';
import {
    Calendar,
    CollectionTag,
    Wallet
} from '@element-plus/icons-vue';

import * as echarts from 'echarts/core';
import { LineChart, BarChart, PieChart } from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    ToolboxComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    ToolboxComponent,
    LineChart,
    BarChart,
    PieChart,
    CanvasRenderer,
]);

const loading = ref(true);
const overviewData = ref<any>(null);
const chartsInitialized = ref({
    monthly: false,
    capital: false
});

// 定时器变量，用于定时刷新数据
let refreshTimer: number | null = null;
// 刷新间隔时间（毫秒），这里设置为30秒
const REFRESH_INTERVAL = 30000;

// ECharts 实例
const monthlyReturnChartInstance = shallowRef<echarts.ECharts | null>(null);
const capitalDistChartInstance = shallowRef<echarts.ECharts | null>(null);

// ECharts DOM 引用
const monthlyReturnChartRef = ref<HTMLElement | null>(null);
const capitalDistChartRef = ref<HTMLElement | null>(null);

const formatCurrency = (value: number) => {
    if (value === null || value === undefined) return 'N/A';
    if (typeof value !== 'number') return String(value);
    return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const formatPercent = (value: number, digits: number = 2) => {
    if (value === null || value === undefined) return 'N/A';
    if (typeof value !== 'number') return String(value);
    return `${value.toFixed(digits)}%`;
};

const formatTime = (isoString: string, short: boolean = false) => {
    if (!isoString) return 'N/A';
    try {
        const date = new Date(isoString);

        // 确保时间有效
        if (isNaN(date.getTime())) {
            return isoString;
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        if (short) {
            return `${month}-${day} ${hours}:${minutes}`;
        } else {
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    } catch (e) {
        console.error('时间格式化错误:', e);
        return isoString;
    }
};



const monthlyReturnChartOption = computed((): EChartsOption => {
    const returns = overviewData.value?.monthly_returns || [];
    // 计算当前收益额的平均状态，决定图例颜色
    const hasPositiveReturns = returns.some((item: any) => item.profit_amount >= 0);
    // 如果有正负收益，使用绿色作为图例默认颜色
    // 如果全部是负收益，使用红色
    const profitLegendColor = hasPositiveReturns ? '#67C23A' : '#F56C6C';

    return {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross', crossStyle: { color: '#999' } },
            formatter: (params: any) => {
                const date = params[0].name;
                const profit = params[0].value;
                const rate = params[1].value;
                return `${date}<br/>收益额: ${formatCurrency(profit)}<br/>收益率: ${formatPercent(rate, 2)}`;
            },
        },
        legend: {
            data: ['收益额 (USD)', '收益率 (%)'],
            top: 10,
        },
        grid: { left: '3%', right: '4%', bottom: '3%', top: 60, outerBounds: {} },
        xAxis: [
            {
                type: 'category',
                data: returns.map((item: any) => item.month),
                axisPointer: { type: 'shadow' },
                axisLabel: { rotate: 45 },
            },
        ],
        yAxis: [
            {
                type: 'value',
                name: '收益额',
                axisLabel: { formatter: (value: number) => `${(value / 1000).toFixed(0)}k` },
            },
            {
                type: 'value',
                name: '收益率',
                axisLabel: { formatter: '{value} %' },
            },
        ],
        series: [
            {
                name: '收益额 (USD)',
                type: 'bar',
                data: returns.map((item: any) => ({
                    value: item.profit_amount,
                    itemStyle: {
                        color: item.profit_amount >= 0 ? '#67C23A' : '#F56C6C'
                    }
                })),
                // 确保图例颜色与柱状图主要颜色一致
                itemStyle: {
                    color: profitLegendColor
                }
            },
            {
                name: '收益率 (%)',
                type: 'line',
                yAxisIndex: 1,
                smooth: true,
                data: returns.map((item: any) => item.return_rate),
                lineStyle: {
                    color: '#E6A23C'
                },
                itemStyle: {
                    color: '#E6A23C'
                }
            },
        ],
    };
});

const capitalDistChartOption = computed((): EChartsOption => {
    const distribution = overviewData.value?.capital_status.exchange_distribution || [];
    return {
        tooltip: {
            trigger: 'item',
            formatter: '{b} <br/>{c} USD ({d}%)',
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'center',
            formatter: (name: string) => {
                const item = distribution.find((d: any) => d.exchange_name === name);
                return `${name} ${item?.percentage || 0}%`;
            }
        },
        series: [
            {
                name: '交易所分布',
                type: 'pie',
                radius: ['50%', '80%'],
                center: ['65%', '50%'],
                avoidLabelOverlap: false,
                label: { show: false },
                labelLine: { show: false },
                data: distribution.map((item: any) => ({
                    value: item.amount,
                    name: item.exchange_name,
                })),
            },
        ],
    };
});

const initOrUpdateChart = (dom: HTMLElement | null, instanceRef: any, option: EChartsOption, keyName: 'monthly' | 'capital') => {
    try {
        if (!dom) return;
        // 尝试获取已有实例
        let inst = echarts.getInstanceByDom(dom) as echarts.ECharts | null;
        if (!inst) {
            inst = echarts.init(dom);
            chartsInitialized.value[keyName] = true;
        }
        // 存储实例引用，确保nextTick回调中使用正确的实例
        instanceRef.value = inst;
        // 使用 nextTick 确保在 DOM 更新后执行 setOption 和 resize
        nextTick(() => {
            try {
                // 使用存储的实例引用
                const chartInstance = instanceRef.value;
                if (chartInstance) {
                    // 使用 setOption 更新数据（会合并默认的 option）
                    chartInstance.setOption(option, { notMerge: false });
                    chartInstance.resize();
                }
            } catch (e) {
                console.error('setOption/resize 错误:', e);
            }
        });
    } catch (e) {
        console.error('initOrUpdateChart 错误:', e);
    }
};

const initAllCharts = () => {
    initOrUpdateChart(capitalDistChartRef.value, capitalDistChartInstance, capitalDistChartOption.value, 'capital');
    initOrUpdateChart(monthlyReturnChartRef.value, monthlyReturnChartInstance, monthlyReturnChartOption.value, 'monthly');
};

const handleResize = () => {
    nextTick(() => {
        try {
            monthlyReturnChartInstance.value?.resize();
            capitalDistChartInstance.value?.resize();
        } catch (e) {
            console.warn('resize error', e);
        }
    });
};

onMounted(() => {
    fetchData();
    window.addEventListener('resize', handleResize);

    // 设置定时刷新
    refreshTimer = window.setInterval(() => {
        fetchData();
    }, REFRESH_INTERVAL);
});

onBeforeUnmount(() => {
    try {
        // 释放 echarts 实例
        if (monthlyReturnChartInstance.value) {
            monthlyReturnChartInstance.value.dispose();
            monthlyReturnChartInstance.value = null;
        }
        if (capitalDistChartInstance.value) {
            capitalDistChartInstance.value.dispose();
            capitalDistChartInstance.value = null;
        }
    } catch (e) {
        console.warn('dispose echarts error', e);
    }

    window.removeEventListener('resize', handleResize);

    // 清除定时器，避免内存泄漏
    if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
    }
});

const fetchData = async () => {
    try {
        const response = await getOverview({ days: 30 });
        if (response) {
            // 更新数据
            overviewData.value = response;

            await nextTick();

            // 初始化或更新图表，保证每次数据到来都刷新图表
            initAllCharts();
        } else {
            console.error('获取数据失败: 响应为空');
        }
    } catch (error) {
        console.error('获取首页概览失败:', error);
    } finally {
        loading.value = false;
    }
};
</script>

<style scoped>
.dashboard-container {
    padding: 16px;
    min-height: 100vh;
    background-color: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.6;
    color: #333;
}

@keyframes numberFloat {
    0% {
        transform: translateY(0);
        opacity: 1;
    }

    25% {
        transform: translateY(-2px);
        opacity: 0.95;
    }

    50% {
        transform: translateY(1px);
        opacity: 1;
    }

    75% {
        transform: translateY(-1px);
        opacity: 0.98;
    }

    100% {
        transform: translateY(0);
        opacity: 1;
    }
}

@keyframes numberPositive {
    0% {
        background-color: transparent;
    }

    50% {
        background-color: rgba(103, 194, 58, 0.1);
    }

    100% {
        background-color: transparent;
    }
}

@keyframes numberNegative {
    0% {
        background-color: transparent;
    }

    50% {
        background-color: rgba(245, 108, 108, 0.1);
    }

    100% {
        background-color: transparent;
    }
}

.number-update {
    animation: numberFloat 0.8s ease-in-out;
    border-radius: 4px;
    padding: 2px 4px;
}

.profit-cell.number-update {
    animation: numberFloat 0.8s ease-in-out, numberPositive 0.8s ease-in-out;
}

.loss-cell.number-update {
    animation: numberFloat 0.8s ease-in-out, numberNegative 0.8s ease-in-out;
}

.content-wrapper {
    background-color: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    min-height: calc(100vh - 100px);
}

.el-row {
    margin-bottom: 16px;
    line-height: 1.6;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-card {
    border-radius: 8px;
    border: 1px solid #e9eef3;
}

.card-header {
    font-weight: bold;
    font-size: 17px;
    color: #303133;
    display: flex;
    align-items: center;
    gap: 8px;
}

.stretch-card {
    height: 100%;
}

.system-status-container {
    margin-bottom: 16px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    padding: 12px;
    background-color: #ffffff;
}

.system-status-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #333;
    line-height: 1.5;
}

.profit-loss-text {
    font-weight: 600;
    font-size: 14px;
    display: inline-block;
}

.profit-cell {
    color: #52c41a !important;
    font-weight: 600 !important;
}

.loss-cell {
    color: #ff4d4f !important;
    font-weight: 600 !important;
}

.status-main {
    display: flex;
    align-items: center;
    gap: 16px;
}

.status-badge {
    padding: 3px 10px;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
    letter-spacing: 0.5px;
}

.status-badge.running {
    background-color: #f0f9ff;
    color: #1677ff;
    border: 1px solid #bae0ff;
}

.status-badge.stopped {
    background-color: #fff1f0;
    color: #ff4d4f;
    border: 1px solid #ffccc7;
}

.running-days {
    font-weight: 500;
}

.status-details {
    display: flex;
    align-items: center;
    gap: 20px;
    color: #555;
    font-size: 14px;
}

.error-count {
    color: #ff4d4f;
    font-weight: 500;
}

.warning-count {
    color: #faad14;
    font-weight: 500;
}

@media (max-width: 768px) {
    .system-status-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .status-main {
        gap: 12px;
    }

    .status-details {
        gap: 15px;
        font-size: 13px;
        flex-wrap: wrap;
    }

    .periodic-metric-card .el-statistic,
    .capital-highlight .el-statistic {
        --el-statistic-content-font-size: 26px;
    }

    .kpi-item {
        padding: 10px 8px;
    }

    .kpi-item-label,
    .kpi-item-value {
        font-size: 13px;
    }
}

.l1-periodic-metrics-row .el-col {
    margin-bottom: 10px;
}

.periodic-metric-card {
    min-height: 150px;
    display: flex;
    flex-direction: column;
}

.periodic-metric-card .el-statistic {
    --el-statistic-title-font-size: 16px;
    --el-statistic-content-font-size: 32px;
    --el-statistic-content-font-weight: 600;
    margin-top: 10px;
    line-height: 1.3;
}

.periodic-sub-metric {
    margin-top: 12px;
    font-size: 14px;
    color: #555;
    display: flex;
    justify-content: space-between;
    line-height: 1.4;
}



.metrics-container {
    display: flex;
    gap: 20px;
    width: 100%;
    height: 100%;
    align-items: stretch;
}

.metrics-section {
    flex: 1;
    border-radius: 6px;
    background-color: #fafafa;
    padding: 15px;
    box-sizing: border-box;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.metrics-section.core-metrics {
    background-color: #f0f7ff;
    border: 1px solid #e0efff;
}

.metrics-section.risk-metrics {
    background-color: #fff7f0;
    border: 1px solid #fff0e0;
}

.metrics-content {
    display: flex;
    flex-direction: column;
    gap: 2px;
    width: 100%;
}

@media (max-width: 1024px) {
    .metrics-container {
        gap: 15px;
        min-height: 360px;
    }

    .metrics-section {
        padding: 12px;
    }
}

@media (max-width: 768px) {
    .metrics-container {
        flex-direction: column;
        gap: 12px;
        min-height: auto;
    }

    .metrics-section {
        padding: 10px;
    }

    .kpi-item {
        padding: 10px 8px;
    }

    .kpi-item-label {
        font-size: 13px;
    }

    .kpi-item-value {
        font-size: 14px;
    }
}

.kpi-list {
    display: flex;
    flex-direction: column;
    gap: 5px;
    height: 100%;
}

.kpi-group-title {
    font-size: 16px;
    font-weight: 600;
    color: #222;
    margin-top: 15px;
    margin-bottom: 10px;
    border-bottom: 1px solid #e9eef3;
    padding-bottom: 8px;
    letter-spacing: 0.5px;
}

.kpi-group-title:first-child {
    margin-top: 0;
}

.kpi-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 10px;
    border-bottom: 1px solid #f0f2f5;
    transition: background-color 0.2s;
    line-height: 1.4;
}

.kpi-item:last-child {
    border-bottom: none;
}

.kpi-item:hover {
    background-color: #f9fafc;
}

.kpi-item-label {
    font-size: 14px;
    color: #555;
    font-weight: 400;
}

.kpi-item-value {
    font-size: 15px;
    font-weight: 600;
    color: #222;
    letter-spacing: 0.3px;
}

.strategy-description {
    margin-bottom: 95px;
}

.strategy-description .el-descriptions__row {
    margin-bottom: 8px;
}

.strategy-description .el-descriptions__label {
    padding: 12px 15px;
}

.strategy-description .el-descriptions__content {
    padding: 12px 15px;
}

.strategy-table {
    margin-top: 16px;
}

.strategy-table .el-table__row {
    height: 48px;
}

.strategy-table .el-table__cell {
    padding: 12px 8px;
}

.capital-highlight {
    display: flex;
    justify-content: center;
    margin-bottom: 15px;
    text-align: center;
}

.capital-highlight .el-statistic {
    --el-statistic-title-font-size: 16px;
    --el-statistic-content-font-size: 32px;
    --el-statistic-content-font-weight: 600;
    line-height: 1.3;
}

.pie-chart-container {
    width: 100%;
    height: 220px;
}

.capital-details {
    margin-top: 20px;
}

.chart-container-secondary {
    width: 100%;
    height: 350px;
}

@media (max-width: 768px) {
    .chart-container-secondary {
        height: 280px;
    }
}

@media (max-width: 992px) {

    .l1-periodic-metrics-row .el-col,
    .el-col-lg-24,
    .el-col-lg-12,
    .el-col-lg-8,
    .el-col-lg-16 {
        margin-bottom: 20px;
    }
}

.profit-positive {
    color: var(--el-color-success);
}

.profit-negative {
    color: var(--el-color-danger);
}

.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 500;
    margin-right: 10px;
}

.status-badge.running {
    background-color: rgba(103, 194, 58, 0.15);
    color: var(--el-color-success);
    border: 1px solid rgba(103, 194, 58, 0.3);
}

.status-badge.running::before {
    content: '●';
    display: inline-block;
    animation: pulse 2s infinite;
    margin-right: 4px;
}

.status-badge.wait {
    background-color: rgba(64, 158, 255, 0.15);
    color: var(--el-color-primary);
    border: 1px solid rgba(64, 158, 255, 0.3);
}

.status-badge.wait::before {
    content: '⟳';
    display: inline-block;
    animation: rotate 1.5s linear infinite;
    margin-right: 4px;
}

.status-badge:not(.running):not(.wait) {
    background-color: rgba(144, 147, 153, 0.15);
    color: var(--el-text-color-secondary);
    border: 1px solid rgba(144, 147, 153, 0.3);
}

.status-badge:not(.running):not(.wait)::before {
    content: '○';
    display: inline-block;
    margin-right: 4px;
}

@keyframes pulse {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }

    100% {
        opacity: 1;
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>
